//
//  UUProductPackageListVC.m
//  UUCharterSupplier
//
//  Created by ZhangAo on 26/02/2018.
//  Copyright © 2018 UUCharter. All rights reserved.
//

#import "UUProductPackageListVC.h"
#import "UUProductManager.h"
#import "UUResourceManager.h"
#import "UUPermissionManager.h"
#import "UUBaseTableViewCell.h"
#import "UUProductPackageEditVC.h"

@interface UUProductPackageCell : UUBaseTableViewCell

@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *subtitleLabel;
@property (nonatomic, strong) UILabel *descLabel;

@end

@implementation UUProductPackageCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.nameLabel = [UILabel new];
        self.nameLabel.font = [UIFont systemFontOfSize:16];
        self.nameLabel.textColor = COMMON_TEXT_BLACK_COLOR;
        [self.contentView addSubview:self.nameLabel];
        [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.mas_equalTo(15);
            make.right.mas_equalTo(-15);
            make.height.mas_equalTo(23);
        }];
        
        self.subtitleLabel = [UILabel new];
        self.subtitleLabel.font = [UIFont systemFontOfSize:14];
        self.subtitleLabel.textColor = COMMON_TEXT_LIGHT_COLOR;
        [self.contentView addSubview:self.subtitleLabel];
        [self.subtitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.nameLabel.mas_bottom).offset(10);
            make.left.right.equalTo(self.nameLabel);
            make.height.mas_equalTo(20);
        }];

        self.descLabel = [UILabel new];
        self.descLabel.font = [UIFont systemFontOfSize:14];
        self.descLabel.textColor = COMMON_TEXT_LIGHT_COLOR;
        [self.contentView addSubview:self.descLabel];
        [self.descLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.subtitleLabel.mas_bottom).offset(5);
            make.left.right.equalTo(self.nameLabel);
            make.height.mas_equalTo(20);
        }];
    }
    return self;
}

- (void)setupWithModel:(UUProductPackageModel *)package {
    self.nameLabel.text = package.name;
    
    if (package.type == UUProductPackageTypeLine) {
        self.subtitleLabel.text = [NSString stringWithFormat:@"%@-%@", package.minTime, package.maxTime];
    } else {
        if (package.isHalfDay) {
            self.subtitleLabel.text = [NSString stringWithFormat:@"全天 %@ / %@, 半天 %@ / %@",
                                       [self formatKm:package.allDayKm], [self formatHour:package.allDayHour],
                                       [self formatKm:package.halfDayKm], [self formatHour:package.halfDayHour]];
        } else {
            self.subtitleLabel.text = [NSString stringWithFormat:@"全天 %@ / %@", [self formatKm:package.allDayKm], [self formatHour:package.allDayHour]];
        }
    }
    
    self.descLabel.text = package.desc;
}

- (NSString *)formatKm:(NSInteger)km {
    if (km == 0) {
        return @"不限公里";
    } else {
        return [NSString stringWithFormat:@"%ldkm", km];
    }
}

- (NSString *)formatHour:(NSInteger)hour {
    if (hour == 0) {
        return @"不限时";
    } else {
        return [NSString stringWithFormat:@"%ldh", hour];
    }
}

@end

///////////////////////////////////////////////////////////////////////////

@interface UUProductPackageListVC () <UUProductManagerObserver>

@property (nonatomic, assign) UUProductPackageType packageType;
@property (nonatomic, copy) NSArray<id> *packages;

@end

@implementation UUProductPackageListVC

+ (instancetype)packageListWithPackageType:(UUProductPackageType)packageType {
    UUProductPackageListVC *listVC = [self instanceOfAppropriate];
    listVC.packageType = packageType;
    return listVC;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.tableView registerClass:[UUProductPackageCell class] forCellReuseIdentifier:@"Cell"];
    self.tableView.rowHeight = 105;
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithTitle:GetResourceManager().addIconText
                                                                              target:self
                                                                            selector:@selector(addPackage:)];
    
    [self reload];
    
    [GetProductManager() addObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)addPackage:(id)sender {
    UIAlertAction *packageAction = [UIAlertAction actionWithTitle:@"套餐"
                                                            style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * _Nonnull action) {
                                                              UUProductPackageEditVC *vc = [UUProductPackageEditVC packageEditWithPackageType:UUProductPackageTypeDay];
                                                              vc.editable = YES;
                                                              [self.navigationController pushViewController:vc animated:YES];
                                                          }];
    
    UIAlertAction *lineAction = [UIAlertAction actionWithTitle:@"线路"
                                                         style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction * _Nonnull action) {
                                                           UUProductPackageEditVC *vc = [UUProductPackageEditVC packageEditWithPackageType:UUProductPackageTypeLine];
                                                           vc.editable = YES;
                                                           [self.navigationController pushViewController:vc animated:YES];
                                                       }];
    [UIAlertController presentActionControllerWithTitle:nil actions:@[packageAction, lineAction]];
}

- (void)reload {
    self.packages = [GetProductManager() fetchProductPackagesWithPackageType:self.packageType];
    [self.tableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.packages.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UUProductPackageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    
    NSNumber *packageId = self.packages[indexPath.row];
    
    UUProductPackageModel *package = [GetProductManager() fetchProductPackageModelWithPackageId:packageId];
    [cell setupWithModel:package];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSNumber *packageId = self.packages[indexPath.row];
    
    if (self.didSelectPackageBlock == nil) {
        UUProductPackageEditVC *editVC = [UUProductPackageEditVC packageEditWithPackageId:packageId];
        [self.navigationController pushViewController:editVC animated:YES];
    } else {
        self.didSelectPackageBlock(packageId);
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    return self.didSelectPackageBlock == nil && [GetPermissionManager() checkPermission:UUPermissionFlagProductReadWrite];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSString *typeName = self.packageType == UUProductPackageTypeLine ? @"线路" : @"套餐";
        [UIAlertController presentAlertControllerWithTitle:[NSString stringWithFormat:@"确定删除该%@吗？", typeName] message:nil doneBlock:^{
            NSNumber *packageId = self.packages[indexPath.row];
            
            ShowIndicator();
            WEAK_SELF();
            [GetProductManager() asyncDeletePackageWithPackageId:packageId completeBlock:^(NSError *error) {
                HideIndicatorInView(weakSelf.view);
                
                if (error != nil) {
                    ShowTipsOnView(error.localizedDescription, weakSelf.view);
                }
            }];
        } cancelBlock:nil];
    }
}

#pragma mark - UUProductManagerObserver methods

- (void)productManagerDidUpdatePackages {
    [self reload];
}

- (void)productManagerDidRemovePackages:(NSArray<NSNumber *> *)packages {
    if (self.packages.count > 0) {
        NSMutableArray<NSIndexPath *> *indexPathes = [NSMutableArray array];
        NSMutableIndexSet *indexSet = [NSMutableIndexSet new];
        for (int j = 0; j < packages.count; ++j) {
            for (int i = 0; i < self.packages.count; ++i) {
                if ([self.packages[i] isEqual:packages[j]]) {
                    [indexPathes addObject:[NSIndexPath indexPathForRow:i inSection:0]];
                    [indexSet addIndex:i];
                    break;
                }
            }
        }
        
        NSMutableArray<NSNumber *> *mutablePackages = [self.packages mutableCopy];
        [mutablePackages removeObjectsAtIndexes:indexSet];
        self.packages = mutablePackages;
        [self.tableView deleteRowsAtIndexPaths:indexPathes
                              withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

@end
